//
//  Utils.m
//  BBT
//
//  Created by monkxp on 15/8/24.
//  Copyright (c) 2015年 QCKJ. All rights reserved.
//

#import "Utils.h"
//#include "APService.h"
#import <CommonCrypto/CommonDigest.h>
#import "MBProgressHUD.h"
#include <sys/sysctl.h>

@implementation Utils

+(NSString *)changeTypeWithJson:(id)obj{

    NSData *data = [NSJSONSerialization dataWithJSONObject:obj options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return jsonString;
}

+(void) saveDataToFile:(NSDictionary *)data category:(NSString *)category{
    if (category == nil) {
        return;
    }
    NSString *basePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *fileName = [[NSString alloc] initWithFormat:@"%@.plist",category];
    NSString *dataPath = [basePath stringByAppendingPathComponent:fileName];
    NSData *aData = [NSKeyedArchiver archivedDataWithRootObject:data];
    [aData writeToFile:dataPath atomically:YES];
}

+(NSDictionary *) loadDataFromFile:(NSString *) category{
    if (category == nil) {
        return nil;
    }
    NSString *basePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *fileName = [[NSString alloc] initWithFormat:@"%@.plist",category];
    NSString *dataPath = [basePath stringByAppendingPathComponent:fileName];
    NSDictionary *result = nil;
    NSData *aData = [NSData dataWithContentsOfFile:dataPath];
    if(aData != nil) {
        result = [NSKeyedUnarchiver unarchiveObjectWithData:aData];
    }
    return result;
}

//void registerJPush(NSDictionary *launchOptions) {
//    // Required
//    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
//        //可以添加自定义categories
//        [APService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
//                                                       UIUserNotificationTypeSound |
//                                                       UIUserNotificationTypeAlert)
//                                           categories:nil];
//    } else {
//        //categories 必须为nil
//        [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
//                                                       UIRemoteNotificationTypeSound |
//                                                       UIRemoteNotificationTypeAlert)
//                                           categories:nil];
//    }
//    
//    // Required
//    [APService setupWithOption:launchOptions];
//}

+ (NSString *)md5:(NSString *)str {
    const char* cStr = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (int)strlen(cStr), result);
    NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH];
    for (NSInteger i=0; i<CC_MD5_DIGEST_LENGTH; i++) {
        [ret appendFormat:@"%02x", result[i]];
    }
    return ret;

}


+(NSString*)id2str:(id)obj{
    if (obj==nil || obj==NULL) {
        return @"";
    }
    NSString* str=@"";
    if([obj isKindOfClass:[NSString class]]){
        str=(NSString*)obj;
        if ([str isEqualToString:@"<null>"]) {
            str=@"";
        }
        if ([str isEqualToString:@"(null)"]) {
            str=@"";
        }
        if ([str isEqualToString:@"null"]) {
            str=@"";
        }
    }else if([obj isKindOfClass:[NSNumber class]]){
        str=[NSString stringWithFormat:@"%@",obj];
    }
    return str;
}

+(BOOL)id2bool:(id)obj{
    if (obj==nil || obj==NULL) {
        return NO;
    }
    if([obj isKindOfClass:[NSNumber class]]){
        NSNumber* n=(NSNumber*)obj;
        return n.intValue != 0;
    }else if ([obj isKindOfClass:[NSString class]]) {
        NSString* s=(NSString*)obj;
        return [@"true" isEqualToString:s];
    }else
        return NO;
}

+(int) id2int:(id) obj{
    if(obj==nil || obj==NULL)return 0;
    int i=0;
    if([obj isKindOfClass:[NSString class]]){
        if ([(NSString*)obj isEqualToString:@"<null>"]) {
            return 0;
        }else{
            i=[obj intValue];
        }
    }else if([obj isKindOfClass:[NSNumber class]]){
        i=[(NSNumber*)obj intValue];
    }
    return i;
}

+(float) id2float:(id) obj{
    if(obj==nil || obj==NULL)return 0;
    float i=0.f;
    if([obj isKindOfClass:[NSString class]]){
        if ([(NSString*)obj isEqualToString:@"<null>"]) {
            return 0.f;
        }else{
            i=[obj floatValue];
        }
    }else if([obj isKindOfClass:[NSNumber class]]){
        i=[(NSNumber*)obj floatValue];
    }
    return i;
}


+(void) closeHud{
    AppDelegate* app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    if(app.hud){
        [app.hud hide:YES];
        [app.hud removeFromSuperview];
    }
}

void addHud(UIViewController * target){
    AppDelegate* app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    if(app.hud){
        [Utils closeHud];
        app.hud = nil;
    }
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    if (!window) {
        return;
    }
    if (target) {
        app.hud = [[MBProgressHUD alloc] initWithView:target.view];
    } else {
        app.hud = [[MBProgressHUD alloc] initWithView:window];
    }
    
    [window addSubview:app.hud];
}

+(void)showHudWithTitle:(NSString*)title  target:(UIViewController *)target{
    AppDelegate* app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    addHud(target);
    if (!app.hud) {
        return;
    }
    app.hud.labelText = title;
    [app.hud show:YES];
}

+(void)showHudWithTitle:(NSString*)title delay:(float)seconds target:(UIViewController *)target{
    AppDelegate* app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    addHud(target);
    if (!app.hud) {
        return;
    }
    app.hud.labelText = title;
    [app.hud show:YES];
    app.hud.mode=MBProgressHUDModeText;
    [app.hud hide:YES afterDelay:seconds];
}

+(void)showHudWithTitle:(NSString *)title delay:(float)seconds completionBlock:(dispatch_block_t)block
{
    AppDelegate* app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    addHud(nil);
    if (!app.hud) {
        return;
    }
    app.hud.labelText = title;
    [app.hud showAnimated:(BOOL)NO whileExecutingBlock:^{
        sleep(seconds);
    } completionBlock:^{
        if (block) {
            block();
        }
    }];
}

+(void)alertControllerWithTitle:(NSString *)title
                        message:(NSString *)message
                         target:(UIViewController *)target
                 preferredStyle:(UIAlertControllerStyle)preferredStyle
                actionWithTitle:(NSString *)title1
                          style:(UIAlertActionStyle)style1
                        handler:(dispatch_block_t)handler1
                actionWithTitle:(NSString *)title2
                          style:(UIAlertActionStyle)style2
                        handler:(dispatch_block_t)handler2
                     completion:(dispatch_block_t)completion{
    
    UIAlertController *alertControler = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:preferredStyle];
    if (title1) {
        if (!style1) {
            style1 = UIAlertActionStyleDefault;
        }
        UIAlertAction *alertAction1 = [UIAlertAction actionWithTitle:title1 style:style1 handler:^(UIAlertAction * _Nonnull action) {
            if (handler1) {
                handler1();
            }
        }];
        [alertControler addAction:alertAction1];
    }
    
    if (title2) {
        if (!style2) {
            style2 = UIAlertActionStyleDefault;
        }
        UIAlertAction *alertAction2 = [UIAlertAction actionWithTitle:title2 style:style2 handler:^(UIAlertAction * _Nonnull action) {
            if (handler2) {
                handler2();
            }
        }];
        [alertControler addAction:alertAction2];
    }
    
    if (preferredStyle == UIAlertControllerStyleActionSheet) {
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertControler addAction:cancelAction];
    }
    
    [target presentViewController:alertControler animated:YES completion:^{
        if (completion) {
            completion();
        }
    }];
}

+(NSString *)countNumAndChangeformat:(NSString *)inNum{
    NSArray *numArr = [inNum componentsSeparatedByString:@"."];
    NSString *num = numArr[0];
    int count = 0;
    long long int a = num.longLongValue;
    while (a != 0)    {
        count++;
        a /= 10;
    }
    NSMutableString *string = [NSMutableString stringWithString:num];
    NSMutableString *newstring = [NSMutableString string];
    while (count > 3) {
        count -= 3;
        NSRange rang = NSMakeRange(string.length - 3, 3);
        NSString *str = [string substringWithRange:rang];
        [newstring insertString:str atIndex:0];
        [newstring insertString:@"," atIndex:0];
        [string deleteCharactersInRange:rang];
    }
    [newstring insertString:string atIndex:0];
    if (numArr.count == 1) {
        return [NSString stringWithFormat:@"%@.00元",newstring];
    } else {
        NSString *subNum = numArr[1];
        if (subNum.length > 2) {
            subNum = [subNum substringToIndex:2];
        }
        return [NSString stringWithFormat:@"%@.%@元",newstring,subNum];
    }
    
}

+(UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
}

+(UIImage *)reduceImage:(UIImage *)image percent:(float)percent
{
    NSData *imageData = UIImageJPEGRepresentation(image, percent);
    UIImage *newImage = [UIImage imageWithData:imageData];
    return newImage;
}

+ (BOOL)validateIDCardNumber:(NSString *)value {
    value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    int length =0;
    if (!value) {
        return NO;
    }else {
        length = value.length;
        
        if (length !=15 && length !=18) {
            return NO;
        }
    }
    // 省份代码
    NSArray *areasArray =@[@"11",@"12", @"13",@"14", @"15",@"21", @"22",@"23", @"31",@"32", @"33",@"34", @"35",@"36", @"37",@"41", @"42",@"43", @"44",@"45", @"46",@"50", @"51",@"52", @"53",@"54", @"61",@"62", @"63",@"64", @"65",@"71", @"81",@"82", @"91"];
    
    NSString *valueStart2 = [value substringToIndex:2];
    BOOL areaFlag =NO;
    for (NSString *areaCode in areasArray) {
        if ([areaCode isEqualToString:valueStart2]) {
            areaFlag =YES;
            break;
        }
    }
    
    if (!areaFlag) {
        return false;
    }
    
    
    NSRegularExpression *regularExpression;
    NSUInteger numberofMatch;
    
    int year =0;
    switch (length) {
        case 15:
            year = [value substringWithRange:NSMakeRange(6,2)].intValue +1900;
            
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$"
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:nil];//测试出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$"
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:nil];//测试出生日期的合法性
            }
            numberofMatch = [regularExpression numberOfMatchesInString:value
                                                              options:NSMatchingReportProgress
                                                                range:NSMakeRange(0, value.length)];
            
            if(numberofMatch >0) {
                return YES;
            }else {
                return NO;
            }
        case 18:
            
            year = [value substringWithRange:NSMakeRange(6,4)].intValue;
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$"
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:nil];//测试出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$"
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:nil];//测试出生日期的合法性
            }
            numberofMatch = [regularExpression numberOfMatchesInString:value
                                                              options:NSMatchingReportProgress
                                                                range:NSMakeRange(0, value.length)];
            
            
            if(numberofMatch >0) {
                int S = ([value substringWithRange:NSMakeRange(0,1)].intValue + [value substringWithRange:NSMakeRange(10,1)].intValue) *7 + ([value substringWithRange:NSMakeRange(1,1)].intValue + [value substringWithRange:NSMakeRange(11,1)].intValue) *9 + ([value substringWithRange:NSMakeRange(2,1)].intValue + [value substringWithRange:NSMakeRange(12,1)].intValue) *10 + ([value substringWithRange:NSMakeRange(3,1)].intValue + [value substringWithRange:NSMakeRange(13,1)].intValue) *5 + ([value substringWithRange:NSMakeRange(4,1)].intValue + [value substringWithRange:NSMakeRange(14,1)].intValue) *8 + ([value substringWithRange:NSMakeRange(5,1)].intValue + [value substringWithRange:NSMakeRange(15,1)].intValue) *4 + ([value substringWithRange:NSMakeRange(6,1)].intValue + [value substringWithRange:NSMakeRange(16,1)].intValue) *2 + [value substringWithRange:NSMakeRange(7,1)].intValue *1 + [value substringWithRange:NSMakeRange(8,1)].intValue *6 + [value substringWithRange:NSMakeRange(9,1)].intValue *3;
                int Y = S %11;
                NSString *M =@"F";
                NSString *JYM =@"10X98765432";
                M = [JYM substringWithRange:NSMakeRange(Y,1)];// 判断校验位
                if ([M isEqualToString:[value substringWithRange:NSMakeRange(17,1)]]) {
                    return YES;// 检测ID的校验位
                }else {
                    return NO;
                }
                
            }else {
                return NO;
            }
        default:
            return false;
    }
}

+(NSString *)fixPhoneNo:(NSString *)phoneNo{
    NSString *prefix = [phoneNo substringWithRange:NSMakeRange(0,3)];
    NSString *suffix = [phoneNo substringWithRange:NSMakeRange(7,4)];
    return [NSString stringWithFormat:@"%@****%@",prefix,suffix];
}

+(BOOL)validateMobile:(NSString *)mobileNum{
    //NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    NSString * MOBILE = @"^1\\d{10}$";
     NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    if ([regextestmobile evaluateWithObject:mobileNum] == YES){
        return YES;
    }else{
        return NO;
    }
}


+(NSString *) platform{
    size_t size;
    sysctlbyname("hw.machine",NULL, &size, NULL,0);
    char *machine = malloc(size);
    sysctlbyname("hw.machine", machine, &size,NULL, 0);
    NSString*platform = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];
    free(machine);
    return platform;
}

//+(BOOL) checkLocationServiceEnable{
//    //CLLocationManager *locationManager = [[CLLocationManager alloc] init];
//    if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusDenied) {
//        return NO;
//    }
//    return YES;
//}

+(UIImage *)compressImage:(UIImage *)image toMaxFileSize:(NSInteger)maxFileSize {
    CGFloat compression = 0.7f;
    CGFloat maxCompression = 0.1f;
    NSData *imageData = UIImageJPEGRepresentation(image, compression);
    while ([imageData length] > maxFileSize && compression > maxCompression) {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(image, compression);
    }
    
    UIImage *compressedImage = [UIImage imageWithData:imageData];
    return compressedImage;
}

+(UIImage*)imageWithSize:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}

//+(BOOL)valiMobile:(NSString *)mobile{
//    if (mobile.length != 11)
//    {
//        return NO;
//    }
//    /**
//     * 手机号码:
//     * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[0, 1, 6, 7, 8], 18[0-9]
//     * 移动号段: 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
//     * 联通号段: 130,131,132,145,155,156,170,171,175,176,185,186
//     * 电信号段: 133,149,153,170,173,177,180,181,189
//     */
//    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|7[0135678]|8[0-9])\\d{8}$";
//    /**
//     * 中国移动：China Mobile
//     * 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
//     */
//    NSString *CM = @"^1(3[4-9]|4[7]|5[0-27-9]|7[08]|8[2-478])\\d{8}$";
//    /**
//     * 中国联通：China Unicom
//     * 130,131,132,145,155,156,170,171,175,176,185,186
//     */
//    NSString *CU = @"^1(3[0-2]|4[5]|5[56]|7[0156]|8[56])\\d{8}$";
//    /**
//     * 中国电信：China Telecom
//     * 133,149,153,170,173,177,180,181,189
//     */
//    NSString *CT = @"^1(3[3]|4[9]|53|7[037]|8[019])\\d{8}$";
//    
//    
//    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
//    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
//    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
//    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
//    
//    if (([regextestmobile evaluateWithObject:mobile] == YES)
//        || ([regextestcm evaluateWithObject:mobile] == YES)
//        || ([regextestct evaluateWithObject:mobile] == YES)
//        || ([regextestcu evaluateWithObject:mobile] == YES))
//    {
//        return YES;
//    }
//    else
//    {
//        return NO;
//    }
//    //旧的正则表达式
//    //    if (mobile.length < 11)
//    //    {
//    //        return NO;
//    //    }else{
//    //        /**
//    //         * 移动号段正则表达式
//    //         */
//    //        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
//    //        /**
//    //         * 联通号段正则表达式
//    //         */
//    //        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
//    //        /**
//    //         * 电信号段正则表达式
//    //         */
//    //        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
//    //        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
//    //        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
//    //        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
//    //        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
//    //        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
//    //        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
//    //
//    //        if (isMatch1 || isMatch2 || isMatch3) {
//    //            return YES;
//    //        }else{
//    //            return NO;
//    //        }
//    //    }
//    //    return YES;
//}
+ (NSString *)timeWithTimeIntervalString:(NSString *)timeString{
    // 格式化时间
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"beijing"];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    // 毫秒值转化为秒
    if ([[Utils id2str:timeString] length] < 1) {
        return @"";
    }
    double d = [[Utils id2str:timeString] doubleValue];
    if (d < 10000000000) {
        d *= 1000;
    }
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:d / 1000.0];
    NSString* dateString = [formatter stringFromDate:date];
    return dateString;
}

@end
